package com.example.universita.esami;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public abstract class BaseActivity extends Activity {
	
	static final String nameSharedFile = new String("Profilo");
	String Nomeprefs;
	String Cognomeprefs;
	String Matricolaprefs;
	int err;
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.gestione_profilo:     Profilomod();	break;
            case R.id.exit:     finish(); 		break;
            case R.id.reset:     reset(); 		break;
            case R.id.caricasalva:  SalvaCarica();	break;
            case R.id.about:  About();	break;
        }
        return true;
    }
    
    public void SalvaCarica(){
    	final CharSequence[] items = {getString(R.string.base_salva_profilo), getString(R.string.base_carica_profilo)};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.base_modifica_profilo));
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
             if(item == 0)
            	 Salvafile();
             else Caricafile();
            }
        }).show();
    	
    }
    
    
    public void modificaNome(){
    	Toast.makeText(this, getString(R.string.base_modifica_nome), 5).show();      	
    }
    
    public void Salvafile()
    {
    	File folder = new File(Environment.getExternalStorageDirectory() + "/backup esami/");
        
        if(!folder.exists())
            folder.mkdirs();   
        
        try {
			SavePrefs();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        File currentDB=getApplicationContext().getDatabasePath("iLibretto.db");
        File backupDB = new File(folder+"/backup.db");
    	
        DBlibretto(currentDB, backupDB, folder.getPath(), false);    
    }
    
    public void Caricafile()
    {
    	err=0;
    	File folder = new File(Environment.getExternalStorageDirectory() + "/backup esami/");
        
        if(!folder.exists())
            folder.mkdirs();

        try {
			LoadPrefs();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			err=1;
			e.printStackTrace();
		}
        
        File currentDB=getApplicationContext().getDatabasePath("iLibretto.db");
        File backupDB = new File(folder+"/backup.db");
    	
        DBlibretto(backupDB, currentDB, folder.getPath(), true);  

        if(err == 0){
        	Intent refresh = new Intent(this, MainActivity.class);
        	startActivity(refresh);
        	this.finish();
        }
    }
    

    public void SavePrefs() throws IOException
    {
    	SharedPreferences sp1 = getSharedPreferences(nameSharedFile, MODE_PRIVATE);
    	
    	String Nome = sp1.getString("Nome", "Nessun Valore Inserito");
    	Boolean FlagProcedura = sp1.getBoolean("FlagProcedura", true);
    	String Cognome = sp1.getString("Cognome", "Nessun Valore Inserito");
    	String Matricola = sp1.getString("Matricola", "Nessun Valore Inserito");
    	String Facolta = sp1.getString("Facolta", "Nessun Valore Inserito");
    	String Corso = sp1.getString("Corso", "Nessun Valore Inserito");
    	String Special = sp1.getString("Special", "Nessun Valore Inserito");
    	   
    	try{
        	
        	File profilo = new File(Environment.getExternalStorageDirectory() + "/backup esami/Profilo.txt");
        	
        	if(profilo.exists())
        		profilo.delete();
        	
        	profilo.createNewFile();
        	
        	BufferedWriter buf = new BufferedWriter(new FileWriter(profilo, true)); 
    			    	
	    	buf.append(Nome);
	    	buf.newLine();
	    	buf.append(FlagProcedura.toString());
	    	buf.newLine();
	    	buf.append(Cognome);
	    	buf.newLine();
	    	buf.append(Matricola);
	    	buf.newLine();
	    	buf.append(Facolta);
	    	buf.newLine();
	    	buf.append(Corso);
	    	buf.newLine();
	    	buf.append(Special);
	    	
	    	buf.close();	

    	}catch(Exception e){
    		err=1;
    		e.printStackTrace(System.err);
    		Toast.makeText(this, getString(R.string.base_errore), 5).show();
    	}
    }
    
    public void LoadPrefs() throws IOException
    {
    	File profilo = new File(Environment.getExternalStorageDirectory() + "/backup esami/Profilo.txt");
    	BufferedReader buf = new BufferedReader(new FileReader(profilo));
    	SharedPreferences sp1 = getSharedPreferences(nameSharedFile, MODE_PRIVATE);
    	
    	try {
    			if(profilo.exists())
    			{
    				String Nome = buf.readLine();
    				String FlagProcedura = buf.readLine();
    				String Cognome = buf.readLine();
    				String Matricola = buf.readLine();
    				String Facolta = buf.readLine();
    				String Corso = buf.readLine();
    				String Special = buf.readLine();
    				
    				buf.close();
    				
    				SharedPreferences.Editor editor = sp1.edit();
    				
    				editor.putString("Nome", Nome);
    				editor.putBoolean("FlagProcedura", Boolean.parseBoolean(FlagProcedura));
    				editor.putString("Cognome", Cognome);
    				editor.putString("Matricola", Matricola);
    				editor.putString("Facolta", Facolta);
    				editor.putString("Corso", Corso);
    				editor.putString("Special", Special);
    				   
    				editor.commit();
    				
    				Toast.makeText(this, getString(R.string.ripristino_preferenze), 5).show();
    			}
    			else  { Toast.makeText(this, getString(R.string.errore_backup), 5).show(); err=1; }
			
		} catch (Exception e) {
			err=1;
			Toast.makeText(this, getString(R.string.base_errore), 5).show();
		}
    }
    
     
    public void DBlibretto(File currentDB, File backupDB, String folder, boolean ripristino)
    {  	
    	try {
             if (Environment.getExternalStorageDirectory().canWrite()) 
             {              
                 if(backupDB.exists())
                	 backupDB.delete();

                 if (currentDB.exists()) {
                	 
                     FileChannel src = new FileInputStream(currentDB).getChannel();
                     FileChannel dst = new FileOutputStream(backupDB).getChannel();
                     dst.transferFrom(src, 0, src.size());
                     src.close();
                     dst.close();
                     
                     if(!ripristino)
                     Toast.makeText(this, getString(R.string.backup_ok)+"\n\n" +folder+"/backup.db", Toast.LENGTH_SHORT).show();
                     else	Toast.makeText(this, getString(R.string.backup_ripristinato), Toast.LENGTH_SHORT).show();	 
                 }
                 else      { Toast.makeText(this, getString(R.string.errore_db), Toast.LENGTH_SHORT).show(); err=1; }         
         }
            else { Toast.makeText(this, getString(R.string.errore_memoria), 5).show(); err=1; }
        
    	} catch (Exception e) {
        	Toast.makeText(this,getString(R.string.base_errore), 5).show(); err=1; 
        }
    }  
    
    
    public void Profilomod()
    {
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.modifydialog);
		dialog.setTitle(getString(R.string.base_modifica_profilo));
		
		
		SharedPreferences sp1 = getSharedPreferences(nameSharedFile, MODE_PRIVATE);
    	
    	Nomeprefs = sp1.getString("Nome", "Nessun Valore Inserito");
    	Cognomeprefs = sp1.getString("Cognome", "Nessun Valore Inserito");
    	Matricolaprefs = sp1.getString("Matricola", "Nessun Valore Inserito");
    	
		EditText nome = (EditText) dialog.findViewById(R.id.EditText02);
		EditText cognome = (EditText) dialog.findViewById(R.id.EditText01);
		EditText matricola = (EditText) dialog.findViewById(R.id.editText1);
		
		nome.setText(Nomeprefs);
		cognome.setText(Cognomeprefs);
		matricola.setText(Matricolaprefs);
		
		Button close = (Button) dialog.findViewById(R.id.button2);
		
		close.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		Button save = (Button) dialog.findViewById(R.id.button1);
		
		save.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				EditText nome = (EditText) dialog.findViewById(R.id.EditText02);
				EditText cognome = (EditText) dialog.findViewById(R.id.EditText01);
				EditText matricola = (EditText) dialog.findViewById(R.id.editText1);

				String newname = nome.getText().toString();
				String newcognome = cognome.getText().toString();
				String newmatricola = matricola.getText().toString();
				
				
				if(newname.equals("") || newcognome.equals("") || newmatricola.equals(""))
					Toast.makeText(getApplicationContext(), getString(R.string.base_campi_vuoti), 5).show();
				else if (newname.equals(Nomeprefs) && newcognome.equals(Cognomeprefs) && newmatricola.equals(Matricolaprefs))
				{
					Toast.makeText(getApplicationContext(), getString(R.string.base_profilo_mod), 5).show();
					dialog.dismiss();
				}
				else
				{
				 	SharedPreferences sp1 = getSharedPreferences(nameSharedFile, MODE_PRIVATE);
				 	SharedPreferences.Editor editor = sp1.edit();
				 	
					editor.putString("Nome", nome.getText().toString());			
					editor.putString("Cognome", cognome.getText().toString());
					editor.putString("Matricola", matricola.getText().toString());
					editor.commit();
					
					Toast.makeText(getApplicationContext(),getString(R.string.base_profilo_ok) , 5).show();
					dialog.dismiss();
					
					Intent refresh = new Intent(getApplicationContext(), MainActivity.class);
				    startActivity(refresh);
				    finish();
				}

			}
		});
		
		dialog.show();
    }
    
    public void reset()
    {
    	final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.reset);
		dialog.setTitle(getString(R.string.base_reset_profilo));
		
		dialog.show();
		
		Button close = (Button) dialog.findViewById(R.id.closeb);
		
		close.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		Button reset = (Button) dialog.findViewById(R.id.resetb);
		
		reset.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				SharedPreferences sp1 = getSharedPreferences(nameSharedFile, MODE_PRIVATE);
				SharedPreferences.Editor editor = sp1.edit();
				
				editor.remove("Nome");
				editor.remove("FlagProcedura");
				//editor.putBoolean("FlagProcedura", false);
				editor.remove("Cognome");
				editor.remove("Matricola");
				editor.remove("Facolta");
				editor.remove("Corso");
				editor.remove("Special");
				
				editor.commit();
				
			 	Toast.makeText(getApplicationContext(), getString(R.string.base_profilo_elimina), 5).show();
			 	
			 	getApplicationContext().deleteDatabase("iLibretto.db");
			 	Toast.makeText(getApplicationContext(), getString(R.string.base_database_elimina), 5).show();
			 	
			 	Intent intent = new Intent(getApplicationContext(), ProceduraGuidata.class);
			    startActivity(intent);
			    finish();
			 	
			 	dialog.dismiss();
			}
		});
		
    	
    }
    
    public void About()
    {
    	Dialog alert;
    	AlertDialog.Builder about = new AlertDialog.Builder(this);
    	  
    	about.setTitle(getString(R.string.base_info));
    	about.setIcon(R.drawable.ic_menu_info_details);
  	  
    	about.setNegativeButton("Chiudi", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int which) {
    		}
    	});
    	
    	about.setMessage(getString(R.string.base_info_details));	
	  	
		alert = about.create();
  	  	
  	  	about.show();
    }

}